package com.bjpowernode.crm.workbench.service.serviceimpl;

import com.bjpowernode.crm.setting.dao.UserDao;
import com.bjpowernode.crm.setting.eneity.User;
import com.bjpowernode.crm.util.DateTimeUtil;
import com.bjpowernode.crm.util.UUIDUtil;
import com.bjpowernode.crm.vo.PageinationVO;
import com.bjpowernode.crm.workbench.dao.*;
import com.bjpowernode.crm.workbench.eneity.*;
import com.bjpowernode.crm.workbench.exception.ClueException;
import com.bjpowernode.crm.workbench.service.ClueService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ClueServiceImpl implements ClueService {
    @Autowired
    private UserDao userDao;
    //线索相关
    @Autowired
    private ClueDao clueDao;
    @Autowired
    private ClueRemarkDao clueRemarkDao;
    @Autowired
    private ClueActivityRelationDao clueActivityRelationDao;
    //联系人相关
    @Autowired
    private ContactsDao contactsDao;
    @Autowired
    private ContactsRemarkDao contactsRemarkDao;
    @Autowired
    private ContactsActivityRelationDao contactsActivityRelationDao;
    //客户相关
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerRemarkDao customerRemarkDao;
    //交易相关
    @Autowired
    private TranDao tranDao;
    @Autowired
    private TranHistoryDao tranHistoryDao;

    @Override
    @Transactional
    public List<User> searchUsers() {
        //调用dao,进行用户查询
        List<User> userList=userDao.selectUsers();
        return userList;
    }

    @Override
    @Transactional
    public Boolean insert(Clue clue) throws ClueException {
        Boolean flag=true;
        //调用dao
        int result=clueDao.insert(clue);
        if (result!=1){
            flag =false;
            throw new ClueException("添加线索失败");
        }

        return flag;
    }

    @Override
    @Transactional
    public PageinationVO<Clue> pageList(Map<String, String> clueMap) {
        //获取页码，以及每页记录条数
        int pageNo=Integer.parseInt(clueMap.get("pageNo"));
        int pageSize=Integer.parseInt(clueMap.get("pageSize"));
        //调用dao
        //先查询否和条件的总记录条数
        int title=clueDao.getTitle(clueMap);
        //再查询符合条件的记录
        PageHelper.startPage(pageNo,pageSize);
        List<Clue> clueList=clueDao.queryList(clueMap);
        //将结果封装到vo中
        PageinationVO<Clue> vo=new PageinationVO<>();
        vo.setTitle(title);
        vo.setDataList(clueList);
        return vo;
    }

    @Override
    @Transactional
    public Boolean delete(String[] ids) throws ClueException {
        Boolean flag=true;
        //调用dao
        int result=clueDao.delete(ids);
        if (result!=ids.length){
            flag=false;
            throw new ClueException("线索删除失败");
        }
        return null;
    }

    @Override
    public Clue detail(String id) {
        //调用dao
        Clue clue=clueDao.detail(id);
        return clue;
    }

    @Override
    public List<ClueRemark> getRemarks(String clueId) {
        //调用dao
        List<ClueRemark> remarkList=clueRemarkDao.getRemarks(clueId);
        return remarkList;
    }

    @Override
    public List<Activity> getActivityList(String clueId) {
        //调用dao
        List<Activity> activityList=clueDao.getActivityList(clueId);
        return activityList;
    }

    @Override
    @Transactional
    public Boolean convert(Tran tran, String clueId, String creatBy)throws ClueException {
        Boolean flag=true;
        String createTime= DateTimeUtil.getSysTime();
        //(1) 获取到线索id，通过线索id获取线索对象（线索对象当中封装了线索的信息）
        Clue clue=clueDao.queryById(clueId);
        //(2) 通过线索对象提取客户信息，当该客户不存在的时候，新建客户（根据公司的名称精确匹配，判断该客户是否存在！）
        String company=clue.getCompany();
        Customer customer=customerDao.queryCustomerByName(company);
        if (customer==null){
            //新建一个客户
            customer=new Customer();
            customer.setId(UUIDUtil.getUUID());
            customer.setName(company);
            customer.setCreateBy(creatBy);
            customer.setCreateTime(createTime);
            customer.setDescription(clue.getDescription());
            customer.setAddress(clue.getAddress());
            customer.setNextContactTime(clue.getNextContactTime());
            customer.setOwner(clue.getOwner());
            customer.setPhone(clue.getPhone());
            customer.setWebsite(clue.getWebsite());
            customer.setContactSummary(clue.getContactSummary());
            int result1=customerDao.insertCustomer(customer);
            if (result1!=1){
                flag=false;
                throw new ClueException("线索转化失败");
            }
        }
        //(3) 通过线索对象提取联系人信息，保存联系人
        Contacts contact=new Contacts();
        contact.setId(UUIDUtil.getUUID());
        contact.setAddress(clue.getAddress());
        contact.setAppellation(clue.getAppellation());
        contact.setCreateBy(creatBy);
        contact.setCreateTime(createTime);
        contact.setDescription(clue.getDescription());
        contact.setCustomerId(customer.getId());
        contact.setEmail(clue.getEmail());
        contact.setFullname(clue.getFullname());
        contact.setJob(clue.getJob());
        contact.setMphone(clue.getMphone());
        contact.setOwner(clue.getOwner());
        contact.setSource(clue.getSource());
        contact.setContactSummary(clue.getContactSummary());
        contact.setNextContactTime(clue.getNextContactTime());
        int result2= contactsDao.insertContacts(contact);
        if (result2!=1){
            flag=false;
            throw new ClueException("线索转化失败");
        }
        //(4) 线索备注转换到客户备注以及联系人备注
        //先查询出线索的所有备注
        List<ClueRemark> clueRemarkList=this.getRemarks(clueId);
        //如果线索备注不为空，进行线索转换
        List<CustomerRemark> customerRemarkList=new ArrayList<>();
        List<ContactsRemark> contactsRemarkList=new ArrayList<>();
        if (clueRemarkList.size()!=0){
            for (ClueRemark clueRemark:clueRemarkList){
                //线索备注转为客户备注对象参数
                CustomerRemark customerRemark=new CustomerRemark();
                customerRemark.setId(UUIDUtil.getUUID());
                customerRemark.setNoteContent(clueRemark.getNoteContent());
                customerRemark.setCreateBy(creatBy);
                customerRemark.setCreateTime(createTime);
                customerRemark.setCustomerId(customer.getId());
                customerRemark.setEditFlag("0");
                customerRemarkList.add(customerRemark);
                //线索备注转化为联系人备注参数
                ContactsRemark contactsRemark=new ContactsRemark();
                contactsRemark.setId(UUIDUtil.getUUID());
                contactsRemark.setContactsId(contact.getId());
                contactsRemark.setCreateBy(creatBy);
                contactsRemark.setCreateTime(createTime);
                contactsRemark.setEditFlag("0");
                contactsRemark.setNoteContent(clueRemark.getNoteContent());
                contactsRemarkList.add(contactsRemark);
            }
            //将线索备注转化为客户备注和联系人备注
            int result3=customerRemarkDao.insertCustomerRemark(customerRemarkList);
            if (result3!=customerRemarkList.size()){
                flag=false;
                throw new ClueException("线索转化失败");
            }
            int result4=contactsRemarkDao.insertContactsRemark(contactsRemarkList);
            if (result4!=contactsRemarkList.size()){
                flag=false;
                throw new ClueException("线索转化失败");
            }
        }
        //(5) “线索和市场活动”的关系转换到“联系人和市场活动”的关系
        //根据线索id查询关联的市场活动id
        List<ClueActivityRelation> clueActivityRelationList=clueActivityRelationDao.queryByClueId(clueId);
        List<ContactsActivityRelation> contactsActivityRelationList=new ArrayList<>();
        if (clueActivityRelationList.size()!=0){
            for (ClueActivityRelation clueActivityRelation:clueActivityRelationList){
                //联系人和市场活动的关系信息封装
                ContactsActivityRelation contactsActivityRelation=new ContactsActivityRelation();
                contactsActivityRelation.setId(UUIDUtil.getUUID());
                contactsActivityRelation.setActivityId(clueActivityRelation.getActivityId());
                contactsActivityRelation.setContactsId(contact.getId());
                contactsActivityRelationList.add(contactsActivityRelation);
            }
            //添加联系人和市场活动关系信息
            int result5=contactsActivityRelationDao.insertContactsActivity(contactsActivityRelationList);
            if (result5!=contactsActivityRelationList.size()){
                flag=false;
                throw new ClueException("线索转换失败");
            }
        }
        //(6) 如果有创建交易需求，创建一条交易
        if (tran!=null){
            tran.setContactsId(contact.getId());
            tran.setContactSummary(contact.getContactSummary());
            tran.setDescription(contact.getDescription());
            tran.setNextContactTime(customer.getNextContactTime());
            tran.setSource(contact.getSource());
            tran.setOwner(customer.getOwner());
            tran.setCustomerId(customer.getId());
            int result6=tranDao.insertTran(tran);
            if (result6!=1){
                flag=false;
                throw new ClueException("线索转换失败");
            }
            //(7) 如果创建了交易，则创建一条该交易下的交易历史
            TranHistory history=new TranHistory();
            history.setId(UUIDUtil.getUUID());
            history.setCreateBy(creatBy);
            history.setCreateTime(createTime);
            history.setExpectedDate(tran.getExpectedDate());
            history.setMoney(tran.getMoney());
            history.setStage(tran.getStage());
            history.setTranId(tran.getId());
            int result7=tranHistoryDao.insertHistory(history);
            if (result7!=1){
                flag=false;
                throw new ClueException("线索转换失败");
            }
        }
        //(8) 删除线索备注;通过id批量删除
        if (clueRemarkList.size()!=0){
            int result8=clueRemarkDao.deleteClueRemarkList(clueRemarkList);
            if (result8!=clueRemarkList.size()){
                flag=false;
                throw new ClueException("线索转换失败");
            }
        }
        //(9) 删除线索和市场活动的关系
        if (clueActivityRelationList.size()!=0){
            int result9=clueActivityRelationDao.deleteClueActivityRelation(clueId);
            if (result9!=clueActivityRelationList.size()){
                flag=false;
                throw new ClueException("线索转换失败");
            }
        }
        //(10) 删除线索
        int result10=clueDao.deleteById(clueId);
        if (result10!=1){
            flag=false;
            throw new ClueException("线索转换失败");
        }
        return flag;
    }
}
